/*
 * @Author: your name
 * @Date: 2021-06-07 09:42:42
 * @LastEditTime: 2021-06-16 16:13:39
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \CPP\UDP\clientsocket.cpp
 */
#include "clientsocket.h"


ClientSocket::ClientSocket(char* str_port,char* des_ip)
{
    //判断端口号
    int port = atoi(str_port);
    if( port<1025 || port>65535 )//0~1024一般给系统使用，一共可以分配到65535
	{
		printf("端口号范围应为1025~65535");
		exit(-1);
	}

    //创建udp通信socket
	m_udp_socket_fd = socket(AF_INET, SOCK_DGRAM, 0);
	if(m_udp_socket_fd == -1)
	{
		perror("socket failed!\n");
		exit(-1);
	}

    //设置目的IP地址
    m_dest_addr = {0};
    m_dest_addr.sin_family = AF_INET;//使用IPv4协议
    m_dest_addr.sin_port = htons(port);//设置接收方端口号
    m_dest_addr.sin_addr.s_addr = inet_addr(des_ip); //设置接收方IP 
}

ClientSocket::~ClientSocket()
{
    //关闭udp通信
    close(m_udp_socket_fd);
}

void ClientSocket::clear_Cache()
{
    memset(send_buf,0,MAX_INFO_SIZE);
    memset(recv_buf,0,MAX_INFO_SIZE);
}

bool ClientSocket::send_To_Server()
{
    // cout << "send_length:" << send_length << endl;
    send_length = sizeof(info)+5;
    int sret = sendto(m_udp_socket_fd, send_buf, send_length, 0, (struct sockaddr *)&m_dest_addr,sizeof(m_dest_addr)); 
    // cout << "成功发送：" << sret << endl;
    //直接准备接收
   
    //超时判断,设置超时时间为RECV_TIMEOUT
    struct timeval tv;
    tv.tv_sec = RECV_TIMEOUT;
    tv.tv_usec = 0;
    setsockopt(m_udp_socket_fd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv));
    
    //接收服务器返回的信息
    socklen_t len = sizeof(m_dest_addr);

    // cout << "sizeof(recv_buf):" << sizeof(recv_buf) << endl;
    recv_length = recvfrom(m_udp_socket_fd, recv_buf, sizeof(recv_buf),0,(struct sockaddr *)&m_dest_addr,&len);
    // cout << "成功接收:" << recv_length << endl;
    //打印
    if(recv_length > 0)
    {
        // cout << "recv_length:" << recv_length << endl;
        // cout << "recv:" ;
        // puts(recv_buf);
        return true;
    } 
    else
    {
        cout << "服务器繁忙,请稍后再次尝试" << endl;
        return false;
    }
    
    
}

